﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ywxt.Common;

namespace ZJK.Controllers.ExpertManage
{
    using NHibernate;
    using NHibernate.Criterion;
    using NHibernate.Linq;
    using DB_NH;
    using ZJK.Models.ExpertManage;
    using System.IO;

    [Authorize(Roles = "--")]
    public class ExpertManageController : Controller
    {

        #region 专家首页INDEX
        //
        // GET: /ExpertRegister/

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 查询专家的条件记录
        /// </summary>
        public class clsQueryCondictionForExpert
        {
            /// <summary>
            /// 查询的专家姓名
            /// </summary>
            public string qName { get; set; }

            /// <summary>
            /// 查询的专家单位
            /// </summary>
            public string qCompany { get; set; }

            /// <summary>
            /// 查询的专家专业
            /// </summary>
            public string qProfessional { get; set; }

            /// <summary>
            /// 查询的专家状态，在用、停用
            /// </summary>
            public string qStatus { get; set; }

            /// <summary>
            /// 查询的专家分类ID列表，以逗号分割
            /// </summary>
            public string qCategoryIDs { get; set; }

            /// <summary>
            /// 每页记录数量
            /// </summary>
            public int pageSize { get; set; }

            /// <summary>
            /// 页索引
            /// </summary>
            public int pageIndex { get; set; }
        }

        /// <summary>
        /// 专家信息类
        /// </summary>
        public class clsExpert
        {
            /// <summary>
            /// 行索引
            /// </summary>
            public int rowIDX { get; set; }

            /// <summary>
            /// 专家ID
            /// </summary>
            public string ID { get; set; }

            /// <summary>
            /// 专家姓名
            /// </summary>
            public string Name { get; set; }

            /// <summary>
            /// 专家专业
            /// </summary>
            public string Professional { get; set; }

            /// <summary>
            /// 专家手机号码
            /// </summary>
            public string Mobile { get; set; }

            /// <summary>
            /// 专家固定电话
            /// </summary>
            public string TeleWork { get; set; }

            /// <summary>
            /// 专家职称
            /// </summary>
            public string Title { get; set; }

            /// <summary>
            /// 专家工作单位
            /// </summary>
            public string Company { get; set; }

            /// <summary>
            /// 专家所属分类
            /// </summary>
            public string Categorys { get; set; }

            /// <summary>
            /// 专家备注
            /// </summary>
            public string Describe { get; set; }

            /// <summary>
            /// 专家附件
            /// </summary>
            public List<string> Attachments { get; set; }
        }

        /// <summary>
        /// 包含查询专家信息的JSON结果
        /// </summary>
        public class clsJsonResultForExpert : ZJK.Models.clsCommonJsonResult
        {
            public clsExpert expert { get; set; }

            public clsJsonResultForExpert()
            {
                expert = new clsExpert();
            }
        }

        /// <summary>
        /// 包含查询专家记录列表的JSON结果
        /// </summary>
        public class clsJsonResultForExperts : ZJK.Models.clsCommonJsonResult
        {
            /// <summary>
            /// 记录总数
            /// </summary>
            public int recordCount { get; set; }

            /// <summary>
            /// 当前查询结果记录的列表
            /// </summary>
            public List<clsExpert> experts { get; set; }

            public clsJsonResultForExperts()
            {
                experts = new List<clsExpert>();
            }
        }

        /// <summary>
        /// 根据条件，获取专家列表
        /// </summary>
        /// <param name="condiction"></param>
        /// <returns></returns>
        public JsonResult getExperts(clsQueryCondictionForExpert condiction)
        {
            clsJsonResultForExperts _returnValue = new clsJsonResultForExperts();

            if (condiction != null)
            {
                var sessionFactory = SessionFactory.GetCurrentFactory();
                using (var session = sessionFactory.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        try
                        {
                            //专家ID列表
                            List<string> _expert_ids = new List<string>();

                            var _result = new List<DB_NH.DB_Model.ZJK.ZJ_expert>();

                            var _query = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_expert>()
                                .Select(c => c.Id)
                                .Where(c => c.IsValid == 1);

                            //姓名条件
                            if (!string.IsNullOrEmpty(condiction.qName))
                            {
                                _query = _query.And(c => c.zj_name.IsLike("%" + condiction.qName + "%"));
                            }

                            //在用状态条件
                            if (!string.IsNullOrEmpty(condiction.qStatus))
                            {
                                if (condiction.qStatus == "在用")
                                {
                                    //在用
                                    _query = _query.And(c => c.zj_stop_status == DB_NH.DB_Common.ZJKConst.EXP_STOP_STATUS.USED);
                                }
                                else
                                {
                                    //停用
                                    _query = _query.And(c => c.zj_stop_status == DB_NH.DB_Common.ZJKConst.EXP_STOP_STATUS.unUSED);
                                }
                            }

                            //拼凑单位选项
                            if (!string.IsNullOrEmpty(condiction.qCompany))
                            {
                                _query = _query.And(c => c.zj_company.IsLike("%" + condiction.qCompany + "%"));
                            }

                            //拼凑专业选项
                            if (!string.IsNullOrEmpty(condiction.qProfessional))
                            {
                                string[] professions = condiction.qProfessional.Split(new char[] { ',', ';', ' ' });
                                if (professions.Length > 0)
                                {
                                    #region 按专家专业进行查询专家列表，专业以逗号进行分割
                                    //添加专业查询条件的or
                                    var x = new Disjunction();
                                    foreach (string _p in professions)
                                    {
                                        x.Add(Restrictions.On<DB_NH.DB_Model.ZJK.ZJ_expert>(c => c.zj_professional).IsLike(_p, MatchMode.Anywhere));
                                    }

                                    _query = _query.And(x);
                                    #endregion
                                }
                            }

                            //按专家分类查询
                            if (!string.IsNullOrEmpty(condiction.qCategoryIDs))
                            {
                                #region 按专家分类进行查询专家列表，专家分类以逗号进行分割
                                string[] categoryids = condiction.qCategoryIDs.Split(new char[] { ',', ';' });

                                DB_NH.DB_Model.ZJK.ZJ_category category = null;
                                _query = _query.JoinAlias(x => x.zj_categorys, () => category)
                                    .Where(() => category.Id.IsIn(categoryids) && category.IsValid == 1);
                                #endregion
                            }

                            var _this_ids = _query.List<string>().ToArray();

                            _returnValue.recordCount = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_expert>()
                                .Where(c => c.Id.IsIn(_this_ids))
                                .RowCount();

                            var experts = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_expert>()
                            .Where(c => c.Id.IsIn(_this_ids))
                            .Skip(condiction.pageIndex * condiction.pageSize)
                            .Take(condiction.pageSize)
                            .List();

                            _returnValue.experts = new List<clsExpert>();
                            var idx = condiction.pageIndex * condiction.pageSize;
                            foreach (var c in experts)
                            {
                                idx++;
                                clsExpert _exp = new clsExpert()
                                {
                                    rowIDX = idx,
                                    ID = c.Id,
                                    Company = c.zj_company,
                                    Mobile = c.zj_mobile,
                                    Name = c.zj_name,
                                    Professional = c.zj_professional,
                                    TeleWork = c.zj_tele_work,
                                    Title = c.zj_title,
                                    Describe = c.zj_recommend_describe
                                };

                                //拼凑专家分类
                                foreach (var cate in c.zj_categorys)
                                {
                                    if (string.IsNullOrEmpty(_exp.Categorys))
                                    {
                                        _exp.Categorys = cate.category_name;
                                    }
                                    else
                                    {
                                        _exp.Categorys += "," + cate.category_name;
                                    }
                                }

                                _returnValue.experts.Add(_exp);
                            }

                            _returnValue.ISOK = true;
                            _returnValue.MESSAGE = string.Empty;

                            transaction.Commit();
                        }
                        catch (Exception ex)
                        {
                            if (transaction.IsActive) transaction.Rollback();
                            _returnValue.ISOK = false;
                            _returnValue.MESSAGE = "查询专家库错误！错误代码：" + ex.Message;
                        }
                    }
                }
            }
            else
            {
                _returnValue.ISOK = false;
                _returnValue.MESSAGE = "查询专家库错误！错误代码：查询条件传输错误。";
            }

            return Json(_returnValue, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 获取一个专家信息
        /// </summary>
        /// <param name="expId"></param>
        /// <returns></returns>
        public JsonResult getAExpert(string expId)
        {
            clsJsonResultForExpert _returnValue = new clsJsonResultForExpert();

            if (!string.IsNullOrEmpty(expId))
            {
                var sessionFactory = SessionFactory.GetCurrentFactory();
                using (var session = sessionFactory.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        try
                        {
                            var _exp = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_expert>()
                                .Where(c => c.Id == expId)
                                .SingleOrDefault();

                            if (_exp != null)
                            {
                                _returnValue.expert.ID = _exp.Id;
                                _returnValue.expert.Company = _exp.zj_company;
                                _returnValue.expert.Mobile = _exp.zj_mobile;
                                _returnValue.expert.Name = _exp.zj_name;
                                _returnValue.expert.Professional = _exp.zj_professional;
                                _returnValue.expert.rowIDX = 0;
                                _returnValue.expert.TeleWork = _exp.zj_tele_work;
                                _returnValue.expert.Title = _exp.zj_title;

                                _returnValue.ISOK = true;
                            }
                            else
                            {
                                _returnValue.ISOK = false;
                                _returnValue.MESSAGE = "专家信息未找到！";
                            }

                            transaction.Commit();
                        }
                        catch
                        {
                            if (transaction.IsActive) transaction.Rollback();
                            _returnValue.ISOK = false;
                            _returnValue.MESSAGE = "专家信息查询错误！";
                        }
                    }
                }
            }

            return Json(_returnValue, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 根据专家姓名查询是否有同名专家
        /// </summary>
        /// <param name="expertName"></param>
        /// <returns></returns>
        public JsonResult checkAExpert(string expertName)
        {
            ZJK.Models.clsCommonJsonResult _returnValue = new ZJK.Models.clsCommonJsonResult();

            if (!string.IsNullOrEmpty(expertName))
            {
                var sessionFactory = SessionFactory.GetCurrentFactory();
                using (var session = sessionFactory.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        try
                        {
                            var _exp = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_expert>()
                                .Where(c => c.IsValid == 1 && c.zj_name == expertName)
                                .SingleOrDefault();

                            if (_exp != null)
                            {
                                _returnValue.MESSAGE = "专家姓名：" + expertName + "在系统中有记录，身份证号码为：" + _exp.zj_idcard_number + "；请确认专家信息是否重名。";
                            }
                            else
                            {
                                _returnValue.MESSAGE = "专家姓名：" + expertName + "可用！";
                            }

                            transaction.Commit();
                        }
                        catch
                        {
                            if (transaction.IsActive) transaction.Rollback();
                            _returnValue.ISOK = false;
                            _returnValue.MESSAGE = "专家信息查询错误！";
                        }
                    }
                }
            }

            return Json(_returnValue, JsonRequestBehavior.AllowGet);
        }
        #endregion

        /// <summary>
        /// 显示专家管理的操作菜单
        /// </summary>
        /// <returns></returns>
        [ChildActionOnly]
        public ActionResult OPMenu()
        {
            return PartialView();
        }

        #region 专家修改
        /// <summary>
        /// 专家修改进入
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize(Roles = "ZJK")]
        public ActionResult Edit(string id)
        {
            var _model = new vmExpertInfo();

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    //获取当前专家记录
                    var _this_expert = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_expert>()
                        .Fetch(c => c.zj_categorys).Eager()
                        .Where(c => c.IsValid == 1 && c.Id == id)
                        .SingleOrDefault();

                    if (_this_expert != null)
                    {
                        _model.zjAreaCity = _this_expert.zj_city;
                        _model.zjAreaProvince = _this_expert.zj_area;
                        _model.zjBirthdayMonth = _this_expert.zj_birthdate_m;
                        _model.zjBirthdayYear = _this_expert.zj_birthdate_y;

                        //设置所属分类
                        string strTemp = string.Empty;
                        foreach (var _c in _this_expert.zj_categorys)
                        {
                            if (string.IsNullOrEmpty(strTemp))
                            {
                                strTemp = _c.Id;
                            }
                            else
                            {
                                strTemp += "," + _c.Id;
                            }
                        }

                        _model.zjCategoryIDs = strTemp;

                        _model.zjCompany = _this_expert.zj_company;
                        _model.zjContentAndProduct = _this_expert.zj_content_and_product;
                        _model.zjDegree = _this_expert.zj_degree;
                        _model.zjEducation = _this_expert.zj_education;
                        _model.zjEMail = _this_expert.zj_email;
                        _model.zjGraduation = _this_expert.zj_graduation;
                        _model.zjID = _this_expert.Id;
                        _model.zjIDCNumber = _this_expert.zj_idcard_number;
                        _model.zjLevel = _this_expert.zj_level;
                        _model.zjMailAddress = _this_expert.zj_mail_address;
                        _model.zjName = _this_expert.zj_name;
                        _model.zjPosition = _this_expert.zj_position;
                        _model.zjProfessional = _this_expert.zj_professional;
                        _model.zjRecommendDepartment = _this_expert.zj_recommend_department;
                        _model.zjRecommendDescribe = _this_expert.zj_recommend_describe;
                        _model.zjResume = _this_expert.zj_resume;
                        _model.zjSex = _this_expert.zj_sex;
                        _model.zjStopDescribe = _this_expert.zj_stop_describe;
                        _model.zjStopStatus = _this_expert.zj_stop_status.ToString();
                        _model.zjTeleFax = _this_expert.zj_fax;
                        _model.zjTeleHome = _this_expert.zj_tele_home;
                        _model.zjTeleMobile = _this_expert.zj_mobile;
                        _model.zjTeleWork = _this_expert.zj_tele_work;
                        _model.zjTitle = _this_expert.zj_title;
                        _model.zjBirthdayYear = _this_expert.zj_birthdate_y;
                        _model.zjBirthdayMonth = _this_expert.zj_birthdate_m;
                    }
                    else
                    {
                        TempData[Common.CONST_TEMPDATA_INF] = "专家（ID：" + id + "）信息未找到！";
                        return RedirectToAction("Index");
                    }

                    transaction.Commit();
                }
            }

            return View(_model);
        }

        /// <summary>
        /// 专家修改保存提交
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(ExpertEdit _model, string[] category_ids)
        {
            if (ModelState.IsValid && _model != null)
            {
                string _msg = string.Empty;
                if (ExpertIsCanSave(_model.expert, out _msg))
                {
                    //保存专家信息
                    var sessionFactory = SessionFactory.GetCurrentFactory();
                    using (var session = sessionFactory.OpenSession())
                    {
                        using (var transaction = session.BeginTransaction())
                        {
                            try
                            {
                                //获取并修改专家信息
                                DB_NH.DB_Model.ZJK.ZJ_expert _this_expert = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_expert>()
                                    .Where(c => c.Id == _model.expert.Id)
                                    .SingleOrDefault();
                                if (_this_expert != null)
                                {
                                    _this_expert.zj_area = _model.expert.zj_area;
                                    _this_expert.zj_birthdate_m = _model.expert.zj_birthdate_m;
                                    _this_expert.zj_birthdate_y = _model.expert.zj_birthdate_y;
                                    _this_expert.zj_city = _model.expert.zj_city;
                                    _this_expert.zj_company = _model.expert.zj_company;
                                    _this_expert.zj_content_and_product = _model.expert.zj_content_and_product;
                                    _this_expert.zj_degree = _model.expert.zj_degree;
                                    _this_expert.zj_education = _model.expert.zj_education;
                                    _this_expert.zj_email = _model.expert.zj_email;
                                    _this_expert.zj_fax = _model.expert.zj_fax;
                                    _this_expert.zj_graduation = _model.expert.zj_graduation;
                                    _this_expert.zj_idcard_number = _model.expert.zj_idcard_number;
                                    _this_expert.zj_level = _model.expert.zj_level;
                                    _this_expert.zj_mail_address = _model.expert.zj_mail_address;
                                    _this_expert.zj_mobile = _model.expert.zj_mobile;
                                    _this_expert.zj_name = _model.expert.zj_name;
                                    _this_expert.zj_position = _model.expert.zj_position;
                                    _this_expert.zj_professional = _model.expert.zj_professional;
                                    _this_expert.zj_recommend_department = _model.expert.zj_recommend_department;
                                    _this_expert.zj_recommend_describe = _model.expert.zj_recommend_describe;
                                    _this_expert.zj_resume = _model.expert.zj_resume;
                                    _this_expert.zj_sex = _model.expert.zj_sex;
                                    _this_expert.zj_tele_home = _model.expert.zj_tele_home;
                                    _this_expert.zj_tele_work = _model.expert.zj_tele_work;
                                    _this_expert.zj_title = _model.expert.zj_title;

                                    //删除当前专家所有旧的分类
                                    foreach (var _c in _this_expert.zj_categorys)
                                    {
                                        for (int i = _c.zj_experts.Count - 1; i >= 0; i--)
                                        {
                                            if (_c.zj_experts[i].Id == _this_expert.Id)
                                            {
                                                _c.zj_experts.RemoveAt(i);
                                            }
                                        }
                                    }
                                    _this_expert.zj_categorys.Clear();

                                    //创建当前专家所有新的分类
                                    IList<DB_NH.DB_Model.ZJK.ZJ_category> _selected_categorys = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_category>()
                                            .Where(c => c.Id.IsIn(category_ids) && c.IsValid == 1)
                                            .List();

                                    foreach (DB_NH.DB_Model.ZJK.ZJ_category _selected_category in _selected_categorys)
                                    {
                                        _selected_category.zj_experts.Add(_this_expert);
                                        _this_expert.zj_categorys.Add(_selected_category);
                                    }

                                    //保存
                                    session.SaveOrUpdate(_this_expert);
                                }
                                else
                                {
                                    TempData[Common.CONST_TEMPDATA_INF] = "专家查询错误。";
                                    return RedirectToAction("Index");
                                }

                                transaction.Commit();
                                TempData[Common.CONST_TEMPDATA_INF] = "修改专家“" + _model.expert.zj_name + "”成功！";
                                return RedirectToAction("Index");
                            }
                            catch (Exception _ex)
                            {
                                if (transaction.IsActive) transaction.Rollback();
                                TempData[Common.CONST_TEMPDATA_ERR] = _ex.Message;
                                return RedirectToAction("Edit");
                            }
                        }
                    }
                }
                else
                {
                    TempData[Common.CONST_TEMPDATA_INF] = _msg;
                    return RedirectToAction("Edit");
                }
            }
            return View(_model);
        }
        #endregion

        #region 专家注册
        [Authorize(Roles = "ZJK")]
        public ActionResult Regist()
        {
            return View();
        }

        /// <summary>
        /// 新注册一个新专家
        /// </summary>
        /// <param name="data">新专家信息</param>
        /// <returns></returns>
        [Authorize(Roles = "ZJK")]
        public JsonResult newAExpert(ZJK.Models.ExpertManage.vmExpertInfo data)
        {
            ZJK.Models.clsCommonJsonResult _returnValue = new Models.clsCommonJsonResult();

            if (data != null)
            {
                var sessionFactory = SessionFactory.GetCurrentFactory();
                using (var session = sessionFactory.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        try
                        {
                            DB_NH.DB_Model.ZJK.ZJ_expert _new_expert = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_expert>()
                                .Where(c => c.IsValid == 1 && c.zj_name == data.zjName)
                                .SingleOrDefault();

                            if (_new_expert != null)
                            {
                                throw new Exception("系统中已包含姓名为“" + data.zjName + "”的专家信息。");
                            }
                            else
                            {
                                _new_expert = new DB_NH.DB_Model.ZJK.ZJ_expert()
                                {
                                    CreateDate = DateTime.Now,
                                    Id = Common.NewID(),
                                    IsValid = 1,
                                    zj_area = data.zjAreaProvince,
                                    zj_birthdate_m = data.zjBirthdayMonth,
                                    zj_birthdate_y = data.zjBirthdayYear,
                                    zj_city = data.zjAreaCity,
                                    zj_company = data.zjCompany,
                                    zj_content_and_product = data.zjContentAndProduct,
                                    zj_degree = data.zjDegree,
                                    zj_education = data.zjEducation,
                                    zj_email = data.zjEMail,
                                    zj_fax = data.zjTeleFax,
                                    zj_graduation = data.zjGraduation,
                                    zj_idcard_number = data.zjIDCNumber,
                                    zj_level = data.zjLevel,
                                    zj_mail_address = data.zjMailAddress,
                                    zj_mobile = data.zjTeleMobile,
                                    zj_name = data.zjName,
                                    zj_position = data.zjPosition,
                                    zj_professional = data.zjProfessional,
                                    zj_recommend_department = data.zjRecommendDepartment,
                                    zj_recommend_describe = data.zjRecommendDescribe,
                                    zj_resume = data.zjResume,
                                    zj_sex = data.zjSex,
                                    zj_stop_describe = data.zjStopDescribe,
                                    zj_stop_status = DB_NH.DB_Common.ZJKConst.EXP_STOP_STATUS.USED,
                                    zj_tele_home = data.zjTeleHome,
                                    zj_tele_work = data.zjTeleWork,
                                    zj_title = data.zjTitle
                                };

                                //设置专家所属分类
                                string[] ids = data.zjCategoryIDs.Split(',');
                                var _catgorys = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_category>()
                                    .Where(c => c.IsValid == 1 &&
                                        c.is_leaf == 1 &&
                                        c.Id.IsIn(ids))
                                    .List();
                                foreach (var _c in _catgorys)
                                {
                                    _c.zj_experts.Add(_new_expert);
                                    _new_expert.zj_categorys.Add(_c);
                                }

                                session.SaveOrUpdate(_new_expert);

                                transaction.Commit();

                                _returnValue.ISOK = true;
                                _returnValue.MESSAGE = string.Empty;
                            }
                        }
                        catch (Exception ex)
                        {
                            if (transaction.IsActive) transaction.Rollback();
                            _returnValue.ISOK = false;
                            _returnValue.MESSAGE = ex.Message;
                        }
                    }
                }
            }
            else
            {
                _returnValue.ISOK = false;
                _returnValue.MESSAGE = "数据错误！";
            }

            return Json(_returnValue, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 修改一个专家信息
        /// </summary>
        /// <param name="data">专家新信息</param>
        /// <returns></returns>
        [Authorize(Roles = "ZJK")]
        public JsonResult editAExpert(ZJK.Models.ExpertManage.vmExpertInfo data)
        {
            ZJK.Models.clsCommonJsonResult _returnValue = new Models.clsCommonJsonResult();

            if (data != null)
            {
                var sessionFactory = SessionFactory.GetCurrentFactory();
                using (var session = sessionFactory.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        try
                        {
                            DB_NH.DB_Model.ZJK.ZJ_expert _expert = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_expert>()
                                .Where(c => c.IsValid == 1 && c.Id == data.zjID)
                                .SingleOrDefault();

                            if (_expert != null)
                            {
                                //清除当前就得专家的分类信息
                                foreach (var _c in _expert.zj_categorys)
                                {
                                    _c.zj_experts.Remove(_expert);
                                }
                                _expert.zj_categorys.Clear();

                                _expert.zj_area = data.zjAreaProvince;
                                _expert.zj_birthdate_m = data.zjBirthdayMonth;
                                _expert.zj_birthdate_y = data.zjBirthdayYear;
                                _expert.zj_city = data.zjAreaCity;
                                _expert.zj_company = data.zjCompany;
                                _expert.zj_content_and_product = data.zjContentAndProduct;
                                _expert.zj_degree = data.zjDegree;
                                _expert.zj_education = data.zjEducation;
                                _expert.zj_email = data.zjEMail;
                                _expert.zj_fax = data.zjTeleFax;
                                _expert.zj_graduation = data.zjGraduation;
                                _expert.zj_idcard_number = data.zjIDCNumber;
                                _expert.zj_level = data.zjLevel;
                                _expert.zj_mail_address = data.zjMailAddress;
                                _expert.zj_mobile = data.zjTeleMobile;
                                _expert.zj_name = data.zjName;
                                _expert.zj_position = data.zjPosition;
                                _expert.zj_professional = data.zjProfessional;
                                _expert.zj_recommend_department = data.zjRecommendDepartment;
                                _expert.zj_recommend_describe = data.zjRecommendDescribe;
                                _expert.zj_resume = data.zjResume;
                                _expert.zj_sex = data.zjSex;
                                _expert.zj_stop_describe = data.zjStopDescribe;
                                _expert.zj_tele_home = data.zjTeleHome;
                                _expert.zj_tele_work = data.zjTeleWork;
                                _expert.zj_title = data.zjTitle;

                                //设置新的专家所属分类
                                string[] ids = data.zjCategoryIDs.Split(',');
                                var _catgorys = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_category>()
                                    .Where(c => c.IsValid == 1 && c.Id.IsIn(ids))
                                    .List();
                                foreach (var _c in _catgorys)
                                {
                                    _c.zj_experts.Add(_expert);
                                    _expert.zj_categorys.Add(_c);
                                }

                                session.SaveOrUpdate(_expert);

                                transaction.Commit();

                                _returnValue.ISOK = true;
                                _returnValue.MESSAGE = string.Empty;
                            }
                            else
                            {
                                _returnValue.ISOK = false;
                                _returnValue.MESSAGE = "专家信息查询错误！";
                            }
                        }
                        catch (Exception ex)
                        {
                            if (transaction.IsActive) transaction.Rollback();
                            _returnValue.ISOK = false;
                            _returnValue.MESSAGE = ex.Message;
                        }
                    }
                }
            }
            else
            {
                _returnValue.ISOK = false;
                _returnValue.MESSAGE = "数据错误！";
            }

            return Json(_returnValue, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 停用一个专家信息
        /// </summary>
        /// <param name="id">专家ID</param>
        /// <param name="stopDescribe">停用描述</param>
        /// <returns></returns>
        [Authorize(Roles = "ZJK")]
        public JsonResult stopAExpert(string id, string stopDescribe)
        {
            ZJK.Models.clsCommonJsonResult _returnValue = new Models.clsCommonJsonResult();

            if (string.IsNullOrEmpty(id))
            {
                var sessionFactory = SessionFactory.GetCurrentFactory();
                using (var session = sessionFactory.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        try
                        {
                            DB_NH.DB_Model.ZJK.ZJ_expert _expert = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_expert>()
                                .Where(c => c.IsValid == 1 && c.Id == id)
                                .SingleOrDefault();

                            if (_expert != null)
                            {
                                _expert.zj_stop_describe = stopDescribe;
                                _expert.zj_stop_status = DB_NH.DB_Common.ZJKConst.EXP_STOP_STATUS.unUSED;

                                session.SaveOrUpdate(_expert);

                                transaction.Commit();

                                _returnValue.ISOK = true;
                                _returnValue.MESSAGE = string.Empty;
                            }
                            else
                            {
                                _returnValue.ISOK = false;
                                _returnValue.MESSAGE = "专家信息查询错误！";
                            }
                        }
                        catch (Exception ex)
                        {
                            if (transaction.IsActive) transaction.Rollback();
                            _returnValue.ISOK = false;
                            _returnValue.MESSAGE = ex.Message;
                        }
                    }
                }
            }
            else
            {
                _returnValue.ISOK = false;
                _returnValue.MESSAGE = "数据错误！";
            }

            return Json(_returnValue, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 启用一个专家信息
        /// </summary>
        /// <param name="id">专家ID</param>
        /// <returns></returns>
        [Authorize(Roles = "ZJK")]
        public JsonResult useAExpert(string id, string stopDescribe)
        {
            ZJK.Models.clsCommonJsonResult _returnValue = new Models.clsCommonJsonResult();

            if (string.IsNullOrEmpty(id))
            {
                var sessionFactory = SessionFactory.GetCurrentFactory();
                using (var session = sessionFactory.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        try
                        {
                            DB_NH.DB_Model.ZJK.ZJ_expert _expert = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_expert>()
                                .Where(c => c.IsValid == 1 && c.Id == id)
                                .SingleOrDefault();

                            if (_expert != null)
                            {
                                _expert.zj_stop_describe = string.Empty;
                                _expert.zj_stop_status = DB_NH.DB_Common.ZJKConst.EXP_STOP_STATUS.USED;

                                session.SaveOrUpdate(_expert);

                                transaction.Commit();

                                _returnValue.ISOK = true;
                                _returnValue.MESSAGE = string.Empty;
                            }
                            else
                            {
                                _returnValue.ISOK = false;
                                _returnValue.MESSAGE = "专家信息查询错误！";
                            }
                        }
                        catch (Exception ex)
                        {
                            if (transaction.IsActive) transaction.Rollback();
                            _returnValue.ISOK = false;
                            _returnValue.MESSAGE = ex.Message;
                        }
                    }
                }
            }
            else
            {
                _returnValue.ISOK = false;
                _returnValue.MESSAGE = "数据错误！";
            }

            return Json(_returnValue, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region 专家推荐表
        public ActionResult Recommend(string id)
        {
            var _model = new ExpertEdit();

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    #region 获取专家信息
                    _model.expert = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_expert>()
                        .Fetch(c => c.zj_categorys).Eager()
                        .Where(c => c.Id == id && c.IsValid == 1)
                        .SingleOrDefault();

                    if (_model != null)
                    {

                    }
                    else
                    {
                        TempData[Common.CONST_TEMPDATA_INF] = "专家信息未找到！";
                        return RedirectToAction("Index");
                    }
                    #endregion

                    transaction.Commit();
                }
            }

            return View(_model);
        }
        #endregion

        #region 专家身份证复印件
        /// <summary>
        /// 根据专家ID，获取专家身份证附件信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Attachment(string id)
        {
            try
            {
                var _model = getAttachmentModel(id);
                return View(_model);
            }
            catch (Exception _ex)
            {
                TempData[Common.CONST_TEMPDATA_ERR] = _ex.Message;
                return RedirectToAction("Index");
            }

        }

        /// <summary>
        /// 保存附件到数据库
        /// </summary>
        /// <param name="_model"></param>
        /// <param name="myFile"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Attachment(ExpertAttechment _model, HttpPostedFileBase myFile)
        {
            if (ModelState.IsValid)
            {
                // Verify that the user selected a file
                if (myFile != null && myFile.ContentLength > 0)
                {
                    //判断文件名是否合法
                    bool fileOK = false;
                    string fileExtension = System.IO.Path.GetExtension(myFile.FileName).ToLower();
                    string[] allowedExtensions = { ".doc", ".xls", ".ppt", ".docx", ".xlsx", ".pptx", ".rar", ".zip", ".7z", ".tif", ".tiff", ".jpg", ".bmp", ".gif", ".png", ".pdf" };
                    for (int i = 0; i < allowedExtensions.Length; i++)
                    {
                        if (fileExtension == allowedExtensions[i])
                        {
                            fileOK = true;
                            break;
                        }
                    }

                    if (fileOK)
                    {
                        //保存文件为byte[]
                        MemoryStream ms = new MemoryStream();
                        myFile.InputStream.CopyTo(ms);
                        byte[] file_datas = ms.GetBuffer();

                        var sessionFactory = SessionFactory.GetCurrentFactory();
                        using (var session = sessionFactory.OpenSession())
                        {
                            using (var transaction = session.BeginTransaction())
                            {
                                #region 获取当前登录用户

                                string _this_user_name_en = Common.getAuthenticatedUser(User).Name;
                                string _this_user_name_cn = Common.getAuthenticatedUser(User).DisplayName;

                                var _this_user = session.QueryOver<DB_NH.DB_Model.ywxt.t_sys_user>()
                                    .Where(c => c.is_valid == 1
                                        && c.user_truename_en == _this_user_name_en
                                        && c.user_truename_cn == _this_user_name_cn)
                                    .SingleOrDefault();

                                if (_this_user == null)
                                
                                {
                                    transaction.Rollback();
                                    TempData[Common.CONST_TEMPDATA_INF] = "当前操作用户信息错误！";
                                    return View(_model);
                                }
                                #endregion

                                #region 获取当前专家记录
                                var _this_exp = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_expert>()
                                    .Where(c => c.IsValid == 1 && c.Id == _model.this_expert_id)
                                    .SingleOrDefault();

                                if (_this_exp != null)
                                {

                                }
                                else
                                {
                                    transaction.Rollback();
                                    TempData[Common.CONST_TEMPDATA_INF] = "当前专家信息错误！";
                                    return View(_model);
                                }
                                #endregion

                                #region 新建并保存一条附件记录
                                var _att = new DB_NH.DB_Model.ywxt.t_attachment()
                                {
                                    att_bytes = file_datas,
                                    att_file_name_current = string.Empty,
                                    att_file_name_original = myFile.FileName,
                                    att_file_sufix = fileExtension,
                                    att_id = Common.NewID(),
                                    att_upload_user = _this_user,
                                    create_date = DateTime.Now,
                                    is_valid = 1
                                };
                                session.SaveOrUpdate(_att);
                                #endregion

                                #region 新建并保存一条专家附件记录，并设置与当前专家、附件关联
                                var _expert_attachment = new DB_NH.DB_Model.ZJK.ZJ_expert_attachment()
                                {
                                    attachment = _att,
                                    expert = _this_exp,
                                    IsValid = 1,
                                    CreateDate = DateTime.Now,
                                    attachment_type = "身份证"
                                };
                                session.SaveOrUpdate(_expert_attachment);
                                #endregion

                                //提交数据库操作
                                transaction.Commit();

                                TempData[Common.CONST_TEMPDATA_INF] = "上传专家【" + _this_exp.zj_name + "】的身份证附件成功！";
                                _model = getAttachmentModel(_model.this_expert_id);
                                return View(_model);
                            }
                        }
                    }
                    else
                    {
                        TempData[Common.CONST_TEMPDATA_INF] = "当前文件类型（" + fileExtension + "）不能上传！";
                        _model = getAttachmentModel(_model.this_expert_id);
                        return View(_model);
                    }
                }
            }

            return View(_model);
        }

        /// <summary>
        /// 根据专家ID、附件ID，删除附件
        /// </summary>
        /// <param name="ExpertId">专家ID</param>
        /// <param name="AttachmentId">附件ID</param>
        /// <returns></returns>
        [Authorize(Roles = "ZJK")]
        public ActionResult AttachmentDel(string ExpertId, string AttachmentId)
        {
            #region 删除当前指定专家附件ID的附件记录
            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    //设置附件记录的有效值
                    var _this_attachment = session.QueryOver<DB_NH.DB_Model.ywxt.t_attachment>()
                        .Where(c => c.is_valid == 1 && c.att_id == AttachmentId)
                        .SingleOrDefault();
                    if (_this_attachment != null)
                    {
                        _this_attachment.is_valid = 0;
                        session.SaveOrUpdate(_this_attachment);
                    }
                    else
                    {
                        transaction.Rollback();
                        TempData[Common.CONST_TEMPDATA_INF] = "参数错误，附件未找到！";
                        return RedirectToAction("Attachment", new { id = ExpertId });
                    }

                    //设置专家附件关联记录的有效值
                    var _this_expert_attachment = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_expert_attachment>()
                        .Where(c => c.attachment.att_id == _this_attachment.att_id &&
                            c.IsValid == 1 &&
                            c.expert.Id == ExpertId)
                        .SingleOrDefault();
                    if (_this_expert_attachment != null)
                    {
                        _this_expert_attachment.IsValid = 0;
                        session.SaveOrUpdate(_this_expert_attachment);
                    }
                    else
                    {
                        transaction.Rollback();
                        TempData[Common.CONST_TEMPDATA_INF] = "参数错误，专家附件记录未找到！";
                        return RedirectToAction("Attachment", new { id = ExpertId });
                    }
                    transaction.Commit();
                    TempData[Common.CONST_TEMPDATA_INF] = "专家附件删除成功！";
                    return RedirectToAction("Attachment", new { id = ExpertId });
                }
            }
            #endregion
        }

        /// <summary>
        /// 根据专家ID，获取专家附件model
        /// </summary>
        /// <param name="_expert_id"></param>
        /// <returns></returns>
        private ExpertAttechment getAttachmentModel(string _expert_id)
        {
            var _model = new ExpertAttechment();

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    #region 查询当前专家信息
                    var _this_expert = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_expert>()
                        .Where(c => c.IsValid == 1 && c.Id == _expert_id)
                        .SingleOrDefault();
                    if (_this_expert != null)
                    {
                        _model.expert = _this_expert;
                        _model.this_expert_id = _this_expert.Id.ToString();
                    }
                    else
                    {
                        throw new Exception("专家（ID：" + _expert_id + "）信息未找到！");
                    }
                    #endregion

                    #region 查询当前专家的所有附件列表
                    var _expert_attachments = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_expert_attachment>()
                        .Where(c => c.expert == _this_expert && c.IsValid == 1)
                        .Fetch(c => c.attachment).Eager()
                        .List();
                    foreach (var c in _expert_attachments)
                    {
                        _model._this_expert_attachments.Add(c.attachment);
                    }
                    #endregion

                    transaction.Commit();
                }
            }
            return _model;
        }
        #endregion

        #region 专家禁用
        /// <summary>
        /// 专家禁用
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Stop(string id)
        {
            var _model = new ExpertStop();

            if (!string.IsNullOrEmpty(id))
            {
                var sessionFactory = SessionFactory.GetCurrentFactory();
                using (var session = sessionFactory.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        var _this_expert = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_expert>()
                            .Where(c => c.IsValid == 1 && c.Id == id)
                            .SingleOrDefault();

                        if (_this_expert != null)
                        {
                            _model.this_expert_id = id;
                            _model.expert = _this_expert;
                            _model.StopStatus = _this_expert.zj_stop_status;
                            _model.StopDescribe = _this_expert.zj_stop_describe;
                        }
                        else
                        {
                            TempData[Common.CONST_TEMPDATA_INF] = "专家（ID：" + id + "）信息未找到！";
                            return RedirectToAction("Index");
                        }

                        //获取当前专家对应的专家分类
                        //获取系统的专家分类列表
                        _model.categorys = _this_expert.zj_categorys.ToList();

                        transaction.Commit();
                    }
                }
            }

            return View(_model);
        }

        [HttpPost]
        public ActionResult Stop(ExpertStop _model)
        {
            if (ModelState.IsValid)
            {
                var sessionFactory = SessionFactory.GetCurrentFactory();
                using (var session = sessionFactory.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        var _this_expert = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_expert>()
                            .Where(c => c.IsValid == 1 && c.Id == _model.this_expert_id)
                            .SingleOrDefault();

                        if (_this_expert != null)
                        {
                            _this_expert.zj_stop_status = _model.StopStatus;
                            _this_expert.zj_stop_describe = _model.StopDescribe;
                            session.SaveOrUpdate(_this_expert);
                            transaction.Commit();

                            TempData[Common.CONST_TEMPDATA_INF] = "专家禁用状态设置完成。";
                            return RedirectToAction("Index");
                        }
                        else
                        {
                            transaction.Commit();

                            TempData[Common.CONST_TEMPDATA_INF] = "专家查询错误，请确认参数是否正确。";
                            return View(_model);
                        }

                    }
                }
            }
            return View(_model);
        }
        #endregion

        #region 专家预选
        /// <summary>
        /// 专家预选记录列表
        /// </summary>
        /// <returns></returns>
        public ActionResult ConfirmList()
        {
            ExpertConfirmList model = new ExpertConfirmList();

            return View(model);
        }

        /// <summary>
        /// 专家预选记录列表(传递来的参数)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ConfirmList(ExpertConfirmList model)
        {
            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    //根据项目查询条件，查询项目列表
                    var query = session.QueryOver<DB_NH.DB_Model.ywxt.t_project>()
                        .Where(m => m.is_valid == 1 &&
                            m.is_leaf == 1 && (
                            m.proj_code.IsLike(model.queryCondiction.Q_project_name, MatchMode.End) ||
                            m.proj_code.IsLike(model.queryCondiction.Q_project_name + @"/", MatchMode.Anywhere) ||
                            m.proj_name.IsLike(model.queryCondiction.Q_project_name, MatchMode.Anywhere)));

                    model.recordCount = query.RowCount();
                    if (model.recordCount % model.pageSize == 0)
                    {
                        model.pageCount = model.recordCount / model.pageSize;
                    }
                    else
                    {
                        model.pageCount = model.recordCount / model.pageSize + 1;
                    }

                    if (model.pageIndex >= model.pageCount)
                    {
                        model.pageIndex = model.pageCount - 1;
                    }

                    var _projs = query
                        .OrderBy(m => m.ProjectYear).Desc()
                        .OrderBy(m => m.proj_order_flag).Desc()
                        .OrderBy(m => m.proj_code).Asc()
                        .Skip(model.pageIndex * model.pageSize)
                        .Take(model.pageSize)
                        .List();

                    foreach (var _p in _projs)
                    {
                        ExpertConfirmList.projectExtractBak _thisProjectExtractBak = new ExpertConfirmList.projectExtractBak()
                        {
                            projectID = _p.proj_id,
                            projectCode = _p.proj_code,
                            projectName = _p.proj_name
                        };


                        //查询当前项目的抽取备选记录
                        DB_NH.DB_Model.ZJCQ.ZJ_extract_bak _thisExtractBak = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract_bak>()
                            .Where(c => c.IsValid == 1)// &&
                            //c.extract_projects..IsIn(new DB_NH.DB_Model.ywxt.t_project[] { _p }))
                            .OrderBy(c => c.CreateDate).Desc()
                            .JoinQueryOver<DB_NH.DB_Model.ywxt.t_project>(c => c.zj_extract_bak_projects)
                            .Where(c => c.proj_id == _p.proj_id)
                            .Take(1)
                            .SingleOrDefault();

                        if (_thisExtractBak != null)
                        {
                            _thisProjectExtractBak.extractID = _thisExtractBak.Id.ToString();
                            _thisProjectExtractBak.extractTitle = _thisExtractBak.title;
                            _thisProjectExtractBak.createDate = _thisExtractBak.CreateDate;

                            foreach (var _v in _thisExtractBak.details)
                            {
                                ExpertConfirmList.ExtractDetail _detail = new ExpertConfirmList.ExtractDetail()
                                {
                                    expertID = _v.expert.Id.ToString(),
                                    expertIsSelected = _v.is_selected,
                                    expertMobile = _v.expert.zj_mobile,
                                    expertName = _v.expert.zj_name,
                                    extractLog = _v.un_selected_msg
                                };

                                _thisProjectExtractBak.extractDetails.Add(_detail);
                            }
                        }

                        model.projectExtractBaks.Add(_thisProjectExtractBak);
                    }

                    transaction.Commit();
                }
            }
            return View(model);
        }

        /// <summary>
        /// 预选验证列表
        /// </summary>
        /// <param name="proj_id">所要创建抽取备选记录的关联项目ID</param>
        /// <param name="bak_id">所要修改的抽取记录的抽取记录ID</param>
        /// <returns></returns>
        public ActionResult Confirm(string proj_id, string bak_id)
        {
            ExpertConfirm model = new ExpertConfirm();

            if (!string.IsNullOrEmpty(proj_id) && string.IsNullOrEmpty(bak_id))
            {
                //项目编号不为空，备选记录ID为空
                //为当前项目创建新的备选记录，并设置Viewmodel
                var sessionFactory = SessionFactory.GetCurrentFactory();
                using (var session = sessionFactory.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        try
                        {
                            #region 创建新的抽取记录
                            //根据项目ID获取项目信息
                            var this_proj = session.QueryOver<DB_NH.DB_Model.ywxt.t_project>()
                                .Where(c => c.is_valid == 1 && c.proj_id == proj_id)
                                .SingleOrDefault();
                            if (this_proj == null)
                            {
                                throw new Exception("项目信息未找到！");
                            }

                            string _this_user_name_en = Common.getAuthenticatedUser(User).Name;
                            string _this_user_name_cn = Common.getAuthenticatedUser(User).DisplayName;

                            var this_user = session.QueryOver<DB_NH.DB_Model.ywxt.t_sys_user>()
                                .Where(c => c.is_valid == 1
                                    && c.user_truename_en == _this_user_name_en
                                    && c.user_truename_cn == _this_user_name_cn)
                                .SingleOrDefault();

                            if (this_user == null)
                            {
                                throw new Exception("操作员信息未找到！");
                            }

                            //新建一个抽取备选记录
                            var bak_record = new DB_NH.DB_Model.ZJCQ.ZJ_extract_bak();
                            bak_record.title = DateTime.Now.ToString("yyyy-MM-dd") + "用户" + this_user.user_truename_cn +
                                "设置[" + this_proj.proj_code + "]" + this_proj.proj_name + "等1个项目的抽取设置";
                            bak_record.user = this_user;
                            bak_record.zj_extract_bak_projects.Add(this_proj);
                            //设置一个空的记录
                            bak_record.details = new List<DB_NH.DB_Model.ZJCQ.ZJ_extract_detail_bak>();

                            session.Save(bak_record);
                            #endregion

                            #region 设置ViewModel
                            model.thisExtractRefProjects = new List<ExpertConfirm.RefProject>();
                            model.expertList_bx = new List<ExpertConfirm.ViewModelExpert>();
                            model.extractList = new List<ExpertConfirm.ViewModelExtract>();

                            #region 根据当前项目，获取本级项目的列表
                            string pcode = this_proj.proj_code;
                            pcode = pcode.Substring(0, pcode.IndexOf('/') - 1);
                            var _projs = session.QueryOver<DB_NH.DB_Model.ywxt.t_project>()
                                .Where(c => c.is_valid == 1 && c.is_leaf == 1 && c.proj_code.IsLike("%" + pcode))
                                .List();
                            foreach (var p in _projs)
                            {
                                ExpertConfirm.RefProject _ref_proj = new ExpertConfirm.RefProject();
                                _ref_proj.projectCode = p.proj_code;
                                _ref_proj.projectID = p.proj_id;
                                _ref_proj.projectCode = p.proj_code;
                                _ref_proj.projectIsSelected = this_proj.proj_id == p.proj_id;
                                _ref_proj.projectName = p.proj_name;

                                model.thisExtractRefProjects.Add(_ref_proj);
                            }
                            #endregion
                            #endregion

                            //提交数据
                            transaction.Commit();
                        }
                        catch (Exception _ex)
                        {
                            TempData[Common.CONST_TEMPDATA_INF] = "程序参数错误！";
                            TempData[Common.CONST_TEMPDATA_ERR] = "错误信息：" + _ex.Message;
                            transaction.Rollback();
                        }
                    }
                }
            }
            else if (string.IsNullOrEmpty(proj_id) && !string.IsNullOrEmpty(bak_id))
            {
                //项目编号为空，备选记录ID不为空
                //获取备选记录相关信息，设置Viewmodel
                var sessionFactory = SessionFactory.GetCurrentFactory();
                using (var session = sessionFactory.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        try
                        {
                            #region 按抽取备选ID查询抽取记录
                            //根据抽取备选记录ID，查询备选记录
                            var this_bak = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract_bak>()
                                .Where(c => c.IsValid == 1 && c.Id == bak_id)
                                .SingleOrDefault();
                            if (this_bak == null)
                            {
                                throw new Exception("抽取备选记录信息未找到！");
                            }

                            //根据项目ID获取项目信息
                            var this_bak_projs = this_bak.zj_extract_bak_projects;

                            //获取抽取记录的操作用户
                            var this_bak_user = this_bak.user;
                            #endregion

                            #region 设置ViewModel
                            model.thisExtractRefProjects = new List<ExpertConfirm.RefProject>();
                            model.expertList_bx = new List<ExpertConfirm.ViewModelExpert>();
                            model.extractList = new List<ExpertConfirm.ViewModelExtract>();

                            #region 根据当前项目，获取本级项目的列表
                            if (this_bak_projs.Count <= 0)
                            {
                                throw new Exception("记录错误，关联的项目未指定！");
                            }
                            string pcode = this_bak_projs[0].proj_code;
                            pcode = pcode.Substring(0, pcode.IndexOf('/') - 1);
                            var _projs = session.QueryOver<DB_NH.DB_Model.ywxt.t_project>()
                                .Where(c => c.is_valid == 1 && c.is_leaf == 1 && c.proj_code.IsLike("%" + pcode))
                                .List();
                            foreach (var p in _projs)
                            {
                                ExpertConfirm.RefProject _ref_proj = new ExpertConfirm.RefProject();
                                _ref_proj.projectCode = p.proj_code;
                                _ref_proj.projectID = p.proj_id;
                                _ref_proj.projectCode = p.proj_code;
                                //设置项目列表是否选定
                                _ref_proj.projectIsSelected = false;
                                foreach (var _p in this_bak_projs)
                                {
                                    if (_p.proj_id == p.proj_id)
                                    {
                                        _ref_proj.projectIsSelected = true;
                                        break;
                                    }

                                }
                                _ref_proj.projectName = p.proj_name;

                                model.thisExtractRefProjects.Add(_ref_proj);
                            }
                            #endregion

                            #region 设置抽取备选记录
                            foreach (var d in this_bak.details)
                            {
                                if (d.IsValid == 1)
                                {
                                    ExpertConfirm.ViewModelExtract _detail = new ExpertConfirm.ViewModelExtract();
                                    _detail.ID = d.Id;
                                    _detail.expertInfo.expertID = d.expert.Id;
                                    _detail.expertInfo.expertCategory = d.expert.zj_area;
                                }
                            }
                            #endregion
                            #endregion

                            //提交数据
                            transaction.Commit();
                        }
                        catch (Exception _ex)
                        {
                            TempData[Common.CONST_TEMPDATA_INF] = "程序参数错误！";
                            TempData[Common.CONST_TEMPDATA_ERR] = "错误信息：" + _ex.Message;
                            transaction.Rollback();
                        }
                    }
                }
            }
            else
            {
                //返回参数错误提示
                TempData[Common.CONST_TEMPDATA_INF] = "程序参数错误！";
                //return RedirectToAction("ConfirmList");
            }

            return View(model);
        }

        #region 设置抽取的备选记录
        /// <summary>
        /// 如果proj_id不为空：为指定的项目创建一个新的抽取备选记录
        /// 如果bak_id不为空：设置指定的备选抽取记录
        /// 
        /// 两者只能有一个参数传来
        /// </summary>
        /// <param name="proj_id">指定项目ID</param>
        /// <param name="bak_id">指定备选抽取记录ID</param>
        /// <returns></returns>
        public ActionResult BakForExtract(string proj_id, string bak_id)
        {
            vmBakForExtract model = new vmBakForExtract();

            if (!string.IsNullOrEmpty(proj_id) && string.IsNullOrEmpty(bak_id))
            {
                #region 为指定项目创建备选记录
                var sessionFactory = SessionFactory.GetCurrentFactory();
                using (var session = sessionFactory.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        try
                        {
                            //查询项目
                            var this_proj = session.QueryOver<DB_NH.DB_Model.ywxt.t_project>()
                                .Where(c => c.is_valid == 1 && c.proj_id == proj_id)
                                .SingleOrDefault();
                            if (this_proj == null)
                            {
                                throw new Exception("项目未找到！");
                            }

                            string _this_user_name_en = Common.getAuthenticatedUser(User).Name;
                            string _this_user_name_cn = Common.getAuthenticatedUser(User).DisplayName;

                            var this_user = session.QueryOver<DB_NH.DB_Model.ywxt.t_sys_user>()
                                .Where(c => c.is_valid == 1
                                    && c.user_truename_en == _this_user_name_en
                                    && c.user_truename_cn == _this_user_name_cn)
                                .SingleOrDefault();

                            if (this_user == null)
                            {
                                throw new Exception("操作员信息未找到！");
                            }

                            //新建一个抽取备选记录
                            var bak_record = new DB_NH.DB_Model.ZJCQ.ZJ_extract_bak();
                            bak_record.title = DateTime.Now.ToString("yyyy-MM-dd") + "用户" + this_user.user_truename_cn +
                                "设置[" + this_proj.proj_code + "]" + this_proj.proj_name + "等1个项目的抽取设置";
                            bak_record.user = this_user;
                            bak_record.zj_extract_bak_projects.Add(this_proj);

                            this_proj.proj_extract_baks.Add(bak_record);
                            //设置一个空的记录
                            bak_record.details = new List<DB_NH.DB_Model.ZJCQ.ZJ_extract_detail_bak>();

                            session.Save(bak_record);
                            //session.Save(this_proj);

                            transaction.Commit();

                            //设置Viewmodel
                            model.bak_record_id = bak_record.Id;
                            model.bak_record_proj_ids = string.Empty;
                            foreach (var p in bak_record.zj_extract_bak_projects)
                            {
                                if (string.IsNullOrEmpty(model.bak_record_proj_ids))
                                {
                                    model.bak_record_proj_ids = p.proj_id;
                                }
                                else
                                {
                                    model.bak_record_proj_ids += "," + p.proj_id;
                                }
                            }

                            model.bak_record_user_name = this_user.user_truename_cn;
                            model.bak_record_date = bak_record.CreateDate.ToString("yyyy-MM-dd HH:mm");
                        }
                        catch (Exception _ex)
                        {
                            TempData[Common.CONST_TEMPDATA_INF] = "程序参数错误！";
                            TempData[Common.CONST_TEMPDATA_ERR] = "错误信息：" + _ex.Message;

                            if (transaction.IsActive)
                            {
                                transaction.Rollback();
                            }
                        }
                    }
                }

                #endregion
            }
            else if (string.IsNullOrEmpty(proj_id) && !string.IsNullOrEmpty(bak_id))
            {
                #region 设置指定备选抽取记录
                var sessionFactory = SessionFactory.GetCurrentFactory();
                using (var session = sessionFactory.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        try
                        {
                            //查询抽取记录
                            var bak_record = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract_bak>()
                                .Where(c => c.IsValid == 1 && c.Id == bak_id)
                                .SingleOrDefault();
                            if (bak_record == null)
                            {
                                throw new Exception("抽取备选记录信息未找到！");
                            }

                            model.bak_record_id = bak_record.Id;
                            model.bak_record_date = bak_record.CreateDate.ToString("yyyy-MM-dd HH:mm");

                            if (bak_record.user != null)
                            {
                                model.bak_record_user_name = bak_record.user.user_truename_cn;
                            }

                            model.bak_record_proj_ids = string.Empty;
                            foreach (var p in bak_record.zj_extract_bak_projects)
                            {
                                if (string.IsNullOrEmpty(model.bak_record_proj_ids))
                                {
                                    model.bak_record_proj_ids = p.proj_id;
                                }
                                else
                                {
                                    model.bak_record_proj_ids += "," + p.proj_id;
                                }
                            }


                            transaction.Commit();
                        }
                        catch (Exception _ex)
                        {
                            TempData[Common.CONST_TEMPDATA_INF] = "程序参数错误！";
                            TempData[Common.CONST_TEMPDATA_ERR] = "错误信息：" + _ex.Message;

                            if (transaction.IsActive)
                            {
                                transaction.Rollback();
                            }
                        }
                    }
                }
                #endregion
            }

            return View(model);
        }

        /// <summary>
        /// 抽取备选记录的对应项目信息
        /// </summary>
        private class BakForExtractProject
        {
            /// <summary>
            /// 项目ID
            /// </summary>
            public string proj_id { get; set; }

            /// <summary>
            /// 项目编号
            /// </summary>
            public string proj_code { get; set; }

            /// <summary>
            /// 项目名称
            /// </summary>
            public string proj_name { get; set; }

            /// <summary>
            /// 项目是否被选中
            /// </summary>
            public int proj_is_selected { get; set; }
        }

        /// <summary>
        /// 根据备选记录ID，获取该记录的关联项目列表
        /// </summary>
        /// <param name="bak_id">备选记录ID</param>
        /// <returns></returns>
        public JsonResult BakForExtract_getProjectLists(string bak_id)
        {
            List<BakForExtractProject> _returnValue = new List<BakForExtractProject>();

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    try
                    {
                        var bak_rec = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract_bak>()
                        .Where(c => c.IsValid == 1 && c.Id == bak_id)
                        .SingleOrDefault();
                        if (bak_rec == null)
                        {
                            throw new Exception("记录未找到！");
                        }

                        string _proj_code = string.Empty;
                        if (bak_rec.zj_extract_bak_projects.Count > 0)
                        {
                            _proj_code = bak_rec.zj_extract_bak_projects[0].proj_code;
                            if (_proj_code.IndexOf("/") > 0)
                            {
                                _proj_code = _proj_code.Substring(0, _proj_code.IndexOf("/"));
                            }
                        }

                        var _projs = session.QueryOver<DB_NH.DB_Model.ywxt.t_project>()
                            .Where(c => c.proj_code.IsLike(_proj_code + "%") && c.is_valid == 1 && c.is_leaf == 1)
                            .OrderBy(c => c.proj_code).Asc()
                            .OrderBy(c => c.proj_order_flag).Asc()
                            .List();

                        foreach (var _p in _projs)
                        {
                            BakForExtractProject _extract_project = new BakForExtractProject();
                            _extract_project.proj_id = _p.proj_id;
                            int i = _p.proj_code.IndexOf("/");
                            if (i >= 0)
                            {
                                _extract_project.proj_code = _p.proj_code.Substring(i - 5);
                            }
                            else
                            {
                                _extract_project.proj_code = _p.proj_code.Substring(_p.proj_code.Length - 5);
                            }

                            _extract_project.proj_name = _p.proj_name;

                            //设置项目是否被当前抽取记录所选中
                            _extract_project.proj_is_selected = 0;
                            foreach (var _pp in bak_rec.zj_extract_bak_projects)
                            {
                                if (_pp.proj_id == _p.proj_id)
                                {
                                    _extract_project.proj_is_selected = 1;
                                    break;
                                }
                            }

                            _returnValue.Add(_extract_project);
                        }

                        transaction.Commit();
                    }
                    catch (Exception _ex)
                    {

                        transaction.Rollback();
                        throw _ex;
                    }
                }
            }

            return Json(_returnValue, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 保存当前指定ID的抽取备选记录的关联项目列表
        /// </summary>
        /// <param name="bak_record_id">指定的备选记录</param>
        /// <param name="bak_record_project_ids">关联的项目ID列表，以逗号分割</param>
        /// <returns></returns>
        public JsonResult BakForExtract_saveProjectLists(string bak_record_id, string bak_record_project_ids)
        {
            ZJK.Models.clsCommonJsonResult _returnValue = new Models.clsCommonJsonResult()
            {
                ISOK = true,
                MESSAGE = string.Empty
            };

            if (string.IsNullOrEmpty(bak_record_id) || string.IsNullOrEmpty(bak_record_project_ids))
            {
                _returnValue.ISOK = false;
                _returnValue.MESSAGE = "参数传递错误，未同时指定备选记录ID和关联的项目。";

            }
            else
            {

                var sessionFactory = SessionFactory.GetCurrentFactory();
                using (var session = sessionFactory.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        try
                        {
                            //获取抽取备选记录
                            var bak_record = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract_bak>()
                                .Where(c => c.IsValid == 1 && c.Id == bak_record_id)
                                .SingleOrDefault();

                            //获取关联记录的列表
                            string[] _proj_ids_new = bak_record_project_ids.Split(',');
                            var _projs_new = session.QueryOver<DB_NH.DB_Model.ywxt.t_project>()
                                .Where(c => c.is_valid == 1 && c.proj_id.IsIn(_proj_ids_new))
                                .List();

                            //清空当前备选记录的关联项目中，不包含新勾选的项目
                            foreach (var _p_old in bak_record.zj_extract_bak_projects)
                            {
                                _p_old.proj_extract_baks.Remove(bak_record);
                            }
                            bak_record.zj_extract_bak_projects.Clear();

                            //为当前记录创建关联项目列表
                            foreach (var _p in _projs_new)
                            {
                                _p.proj_extract_baks.Add(bak_record);
                                bak_record.zj_extract_bak_projects.Add(_p);
                            }

                            session.SaveOrUpdate(bak_record);

                            transaction.Commit();
                        }
                        catch (Exception)
                        {
                            _returnValue.ISOK = false;
                            _returnValue.MESSAGE = "操作错误，请联系管理员获取错误信息。";
                            transaction.Rollback();
                        }
                    }
                }
            }

            return Json(_returnValue, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 抽取备选记录中的专家信息类
        /// </summary>
        public class BakForExtract_Expert
        {
            /// <summary>
            /// 专家ID
            /// </summary>
            public string expId { get; set; }

            /// <summary>
            /// 专家姓名
            /// </summary>
            public string expName { get; set; }

            /// <summary>
            /// 专家专业
            /// </summary>
            public string expProfession { get; set; }

            /// <summary>
            /// 专家分类IDs（以逗号分隔）
            /// </summary>
            public string expCategoryIds { get; set; }

            /// <summary>
            /// 专家分类名称（以逗号分隔）
            /// </summary>
            public string expCategoryNames { get; set; }

            /// <summary>
            /// 专家所在公司
            /// </summary>
            public string expCompany { get; set; }

            /// <summary>
            /// 专家手机
            /// </summary>
            public string expMobile { get; set; }

            /// <summary>
            /// 专家固定电话
            /// </summary>
            public string expPhone { get; set; }

            /// <summary>
            /// 专家职称
            /// </summary>
            public string expTitle { get; set; }

            /// <summary>
            /// 专家备注
            /// </summary>
            public string expDescribe { get; set; }
        }

        /// <summary>
        /// 抽取备选记录的详细记录信息类
        /// </summary>
        public class BakForExtract_Detail
        {
            /// <summary>
            /// 详细记录ID
            /// </summary>
            public string Id { get; set; }

            /// <summary>
            /// 是否选中
            /// </summary>
            public int is_selected { get; set; }

            /// <summary>
            /// 非选中提示内容，当选择自动抽取时，在信息提示中显示的专家不能来的信息
            /// </summary>
            public string un_selected_msg { get; set; }

            /// <summary>
            /// 排序标志
            /// </summary>
            public int order_flag { get; set; }

            /// <summary>
            /// 专家ID
            /// </summary>
            public string expId { get; set; }

            /// <summary>
            /// 专家姓名
            /// </summary>
            public string expName { get; set; }

            /// <summary>
            /// 专家专业
            /// </summary>
            public string expProfession { get; set; }

            /// <summary>
            /// 专家分类IDs（以逗号分隔）
            /// </summary>
            public string expCategoryIds { get; set; }

            /// <summary>
            /// 专家分类名称（以逗号分隔）
            /// </summary>
            public string expCategoryNames { get; set; }

            /// <summary>
            /// 专家所在公司
            /// </summary>
            public string expCompany { get; set; }

            /// <summary>
            /// 专家手机
            /// </summary>
            public string expMobile { get; set; }

            /// <summary>
            /// 专家固定电话
            /// </summary>
            public string expPhone { get; set; }

            /// <summary>
            /// 专家职称
            /// </summary>
            public string expTitle { get; set; }
        }

        /// <summary>
        /// 根据专家姓名、专业、所属专业分类，查询备询专家列表
        /// </summary>
        /// <param name="qName">专家姓名</param>
        /// <param name="qProfession">专家专业</param>
        /// <param name="qCategoyIDs">专家所属分类ID列表</param>
        /// <returns></returns>
        public JsonResult BakForExtract_getExperts_bx(string qName, string qProfession, string qCategoryIDs)
        {
            List<BakForExtract_Expert> _returnValue = new List<BakForExtract_Expert>();

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    try
                    {
                        #region 查询专家列表
                        var _result = new List<DB_NH.DB_Model.ZJK.ZJ_expert>();

                        var _query = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_expert>()
                                .Where(c => c.IsValid == 1 &&
                                    c.zj_stop_status == DB_NH.DB_Common.ZJKConst.EXP_STOP_STATUS.USED);

                        //姓名条件
                        if (!string.IsNullOrEmpty(qName))
                        {
                            _query = _query.And(c => c.zj_name.IsLike("%" + qName + "%"));
                        }

                        //专业条件
                        if (!string.IsNullOrEmpty(qProfession))
                        {
                            _query = _query.And(c => c.zj_professional.IsLike("%" + qProfession + "%"));
                        }

                        //分类条件
                        if (!string.IsNullOrEmpty(qCategoryIDs))
                        {
                            //设置ID分类
                            string[] ids = qCategoryIDs.Split(',');

                            var _query2 = _query
                                .OrderBy(c => c.zj_name).Asc()
                                .JoinQueryOver<DB_NH.DB_Model.ZJK.ZJ_category>(c => c.zj_categorys)
                                .Where(x => x.IsValid == 1 && x.Id.IsIn(ids))
                                .TransformUsing(NHibernate.Transform.Transformers.DistinctRootEntity);

                            //查询记录
                            _result = _query2
                                .List().ToList();
                        }
                        else
                        {
                            //查询记录
                            _result = _query
                                .OrderBy(c => c.zj_name).Asc()
                                .List().ToList();
                        }

                        foreach (var c in _result)
                        {
                            BakForExtract_Expert _exp = new BakForExtract_Expert()
                            {
                                expId = c.Id,
                                expCompany = c.zj_company,
                                expMobile = c.zj_mobile,
                                expName = c.zj_name,
                                expProfession = c.zj_professional,
                                expPhone = c.zj_tele_work,
                                expTitle = c.zj_title,
                                expDescribe = c.zj_recommend_describe
                            };

                            //拼凑专家分类
                            foreach (var cate in c.zj_categorys)
                            {
                                //ID
                                if (string.IsNullOrEmpty(_exp.expCategoryIds))
                                {
                                    _exp.expCategoryIds = cate.Id;
                                }
                                else
                                {
                                    _exp.expCategoryIds = "," + cate.Id;
                                }
                                //Name
                                if (string.IsNullOrEmpty(_exp.expCategoryNames))
                                {
                                    _exp.expCategoryNames = cate.category_name;
                                }
                                else
                                {
                                    _exp.expCategoryNames = "," + cate.category_name;
                                }
                            }

                            _returnValue.Add(_exp);
                        }

                        #endregion
                        transaction.Commit();
                    }
                    catch (Exception)
                    {
                        transaction.Rollback();
                    }
                }
            }

            return Json(_returnValue, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 查询抽取备选记录的详细记录
        /// </summary>
        /// <param name="bak_id">当前的抽取备选记录</param>
        /// <returns></returns>
        public JsonResult BakForExtract_getDetails(string bak_id)
        {
            List<BakForExtract_Detail> _returnValue = new List<BakForExtract_Detail>();

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    try
                    {
                        var _details = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract_detail_bak>()
                            .Where(c => c.IsValid == 1 && c.extract_bak.Id == bak_id)
                            .OrderBy(c => c.order_flag).Asc()
                            .List();

                        foreach (var _d in _details)
                        {
                            BakForExtract_Detail _xd = new BakForExtract_Detail();
                            _xd.Id = _d.Id;
                            _xd.is_selected = _d.is_selected;
                            _xd.order_flag = _d.order_flag;
                            _xd.un_selected_msg = _d.un_selected_msg;
                            _xd.expId = _d.expert.Id;
                            _xd.expMobile = _d.exp_new_mobile;
                            _xd.expCompany = _d.expert.zj_company;
                            _xd.expName = _d.expert.zj_name;
                            _xd.expProfession = _d.exp_new_profession;

                            string strTmp_id = string.Empty;
                            string strTmp_name = string.Empty;
                            foreach (var _c in _d.exp_new_categorys)
                            {
                                if (string.IsNullOrEmpty(strTmp_id))
                                {
                                    strTmp_id = _c.Id;
                                }
                                else
                                {
                                    strTmp_id += "," + _c.Id;
                                }
                                if (string.IsNullOrEmpty(strTmp_name))
                                {
                                    strTmp_name = _c.category_name;
                                }
                                else
                                {
                                    strTmp_name += "," + _c.category_name;
                                }
                            }
                            _xd.expCategoryIds = strTmp_id;
                            _xd.expCategoryNames = strTmp_name;

                            _returnValue.Add(_xd);
                        }
                        transaction.Commit();
                    }
                    catch (Exception)
                    {
                        transaction.Rollback();
                    }
                }
            }

            return Json(_returnValue, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 根据ID，查询一条抽取备选记录的详细记录
        /// </summary>
        /// <param name="detail_id">当前的抽取备选记录</param>
        /// <returns></returns>
        public JsonResult BakForExtract_getDetail(string detail_id)
        {
            BakForExtract_Detail _returnValue = new BakForExtract_Detail();

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    try
                    {
                        var _detail = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract_detail_bak>()
                            .Where(c => c.IsValid == 1 && c.Id == detail_id)
                            .SingleOrDefault();

                        if (_detail == null)
                        {
                            throw new Exception("记录未找到。");
                        }

                        _returnValue.Id = _detail.Id;
                        _returnValue.is_selected = _detail.is_selected;
                        _returnValue.order_flag = _detail.order_flag;
                        _returnValue.un_selected_msg = _detail.un_selected_msg;
                        _returnValue.expId = _detail.expert.Id;
                        _returnValue.expMobile = _detail.exp_new_mobile;
                        _returnValue.expCompany = _detail.expert.zj_company;
                        _returnValue.expName = _detail.expert.zj_name;
                        _returnValue.expProfession = _detail.exp_new_profession;

                        string strTmp_id = string.Empty;
                        string strTmp_name = string.Empty;
                        foreach (var _c in _detail.exp_new_categorys)
                        {
                            if (string.IsNullOrEmpty(strTmp_id))
                            {
                                strTmp_id = _c.Id;
                            }
                            else
                            {
                                strTmp_id += "," + _c.Id;
                            }
                            if (string.IsNullOrEmpty(strTmp_name))
                            {
                                strTmp_name = _c.category_name;
                            }
                            else
                            {
                                strTmp_name += "," + _c.category_name;
                            }
                        }
                        _returnValue.expCategoryIds = strTmp_id;
                        _returnValue.expCategoryNames = strTmp_name;

                        transaction.Commit();
                    }
                    catch (Exception)
                    {
                        transaction.Rollback();
                    }
                }
            }

            return Json(_returnValue, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 为抽取备选记录添加一条当前专家ID的
        /// </summary>
        /// <param name="bak_id"></param>
        /// <param name="expInfo"></param>
        /// <returns></returns>
        public JsonResult BakForExtract_AddDetail(string bak_id, string exp_id)
        {
            ZJK.Models.clsCommonJsonResult _returnValue = new Models.clsCommonJsonResult()
            {
                ISOK = true,
                MESSAGE = string.Empty
            };

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    try
                    {
                        #region 查询抽取备选记录
                        var _bak_record = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract_bak>()
                            .Where(c => c.IsValid == 1 && c.Id == bak_id)
                            .SingleOrDefault();
                        if (_bak_record == null)
                        {
                            throw new Exception("记录未找到！");
                        }
                        #endregion

                        #region 判断当前的专家记录是否已经存在于详细记录列表中
                        foreach (var _d in _bak_record.details)
                        {
                            if (exp_id == _d.expert.Id)
                            {
                                throw new Exception("当前专家记录已经存在，不能重复选取！");
                            }
                        }
                        #endregion

                        #region 查询抽取备选记录的详细记录中最大的orderflag
                        int maxOrderFlag = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract_detail_bak>()
                            .Select(c => c.order_flag)
                            .Where(c => c.extract_bak == _bak_record && c.IsValid == 1)
                            .OrderBy(c => c.order_flag).Desc()
                            .Take(1)
                            .Skip(0)
                            .SingleOrDefault<int>();
                        maxOrderFlag++;
                        #endregion

                        #region 查询专家记录
                        var _exp = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_expert>()
                            .Where(c => c.Id == exp_id && c.IsValid == 1)
                            .SingleOrDefault();
                        if (_exp == null)
                        {
                            throw new Exception("专家记录未找到！");
                        }
                        #endregion

                        #region 添加详细记录
                        DB_NH.DB_Model.ZJCQ.ZJ_extract_detail_bak _detail = new DB_NH.DB_Model.ZJCQ.ZJ_extract_detail_bak();
                        _detail.extract_bak = _bak_record;
                        _detail.expert = _exp;
                        _detail.exp_new_mobile = _exp.zj_mobile;
                        _detail.exp_new_profession = _exp.zj_professional;
                        _detail.order_flag = maxOrderFlag;
                        _detail.un_selected_msg = string.Empty;
                        _detail.is_selected = 1;
                        _detail.exp_new_categorys.Clear();
                        _detail.exp_new_categorys.Clear();
                        foreach (var _c in _exp.zj_categorys)
                        {
                            _detail.exp_new_categorys.Add(_c);
                        }

                        session.SaveOrUpdate(_detail);
                        #endregion
                        transaction.Commit();
                    }
                    catch (Exception _ex)
                    {
                        _returnValue.ISOK = false;
                        _returnValue.MESSAGE = _ex.Message;
                        transaction.Rollback();
                    }
                }
            }

            return Json(_returnValue, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 保存指定专家信息的抽取详细记录到抽取备选记录中；
        /// 如果专家ID在已有的抽取备选记录的详细记录中没有找到，则添加，否则就修改
        /// </summary>
        /// <param name="detail_id">当前的抽取备选记录的详细记录ID</param>
        /// <param name="detailInfo">存有新的抽取详细记录的JSON对象</param>
        /// <returns></returns>
        public JsonResult BakForExtract_SaveDetail(BakForExtract_Detail detailInfo)
        {
            ZJK.Models.clsCommonJsonResult _returnValue = new Models.clsCommonJsonResult()
            {
                ISOK = true,
                MESSAGE = string.Empty
            };

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    try
                    {
                        var _detail = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract_detail_bak>()
                            .Where(c => c.IsValid == 1 && c.Id == detailInfo.Id)
                            .SingleOrDefault();
                        if (_detail == null)
                        {
                            throw new Exception("记录未找到！");
                        }

                        #region 查询抽取备选记录的详细记录中最大的orderflag
                        int maxOrderFlag = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract_detail_bak>()
                            .Select(c => c.order_flag)
                            .Where(c => c.extract_bak == _detail.extract_bak && c.IsValid == 1)
                            .OrderBy(c => c.order_flag).Desc()
                            .Take(1)
                            .Skip(0)
                            .SingleOrDefault<int>();
                        maxOrderFlag++;
                        #endregion

                        #region 修改详细记录
                        _detail.exp_new_categorys.Clear();
                        if (detailInfo.expCategoryIds != null)
                        {
                            string[] c_ids = detailInfo.expCategoryIds.Split(',');
                            var _categorys = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_category>()
                                .Where(c => c.IsValid == 1 && c.Id.IsIn(c_ids))
                                .List();
                            foreach (var _c in _categorys)
                            {
                                _detail.exp_new_categorys.Add(_c);
                            }
                        }

                        _detail.exp_new_mobile = detailInfo.expMobile;
                        _detail.exp_new_profession = detailInfo.expProfession;

                        _detail.is_selected = detailInfo.is_selected;
                        _detail.order_flag = maxOrderFlag;
                        _detail.un_selected_msg = detailInfo.un_selected_msg;

                        session.SaveOrUpdate(_detail);
                        #endregion
                        transaction.Commit();
                    }
                    catch (Exception _ex)
                    {
                        _returnValue.ISOK = false;
                        _returnValue.MESSAGE = _ex.Message;
                        transaction.Rollback();
                    }
                }
            }

            return Json(_returnValue, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 删除指定专家信息的抽取详细记录到抽取备选记录中
        /// </summary>
        /// <param name="detail_id">当前的抽取备选记录的详细记录ID</param>
        /// <param name="expInfo">存有专家信息的JSON对象</param>
        /// <returns></returns>
        public JsonResult BakForExtract_DeleteDetail(string detail_id)
        {
            ZJK.Models.clsCommonJsonResult _returnValue = new Models.clsCommonJsonResult()
            {
                ISOK = true,
                MESSAGE = string.Empty
            };

            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    try
                    {
                        var _detail = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract_detail_bak>()
                            .Where(c => c.IsValid == 1 && c.Id == detail_id)
                            .SingleOrDefault();
                        if (_detail == null)
                        {
                            throw new Exception("记录未找到。");
                        }

                        //删除当前记录
                        _detail.IsValid = 0;
                        _detail.extract_bak.details.Remove(_detail);
                        _detail.extract_bak = null;
                        session.SaveOrUpdate(_detail);

                        transaction.Commit();
                    }
                    catch (Exception _ex)
                    {
                        _returnValue.ISOK = false;
                        _returnValue.MESSAGE = "程序错误，错误代码：" + _ex.Message;
                        transaction.Rollback();
                    }
                }
            }

            return Json(_returnValue, JsonRequestBehavior.AllowGet);
        }
        #endregion

        /// <summary>
        /// 预选验证列表的post提交
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Confirm(ExpertConfirm model, string[] this_extract_ref_projects_yx)
        {
            if (ModelState.IsValid)
            {
                if (model.opFlag == ExpertConfirm.OPType.QUERY_REF_PROJECT)
                {
                    #region 当前操作是查询关联的项目列表
                    var sessionFactory = SessionFactory.GetCurrentFactory();
                    using (var session = sessionFactory.OpenSession())
                    {
                        using (var transaction = session.BeginTransaction())
                        {
                            #region 获取当前选定的项目总项下的所有子项
                            //获取当前选中的项目ID
                            string _this_selected_project_id = model.Q_project_id;
                            if (string.IsNullOrEmpty(_this_selected_project_id))
                            {
                                ViewData[Common.CONST_TEMPDATA_INF] = "没有找到项目ID信息。";
                                return View(model);
                            }

                            //查询当前项目
                            var _this_project = session.QueryOver<DB_NH.DB_Model.ywxt.t_project>()
                                .Where(c => c.proj_id == _this_selected_project_id && c.is_valid == 1)
                                .SingleOrDefault();

                            if (_this_project == null)
                            {
                                ViewData[Common.CONST_TEMPDATA_INF] = "没有找到项目信息。项目ID对应的项目信息未找到！";
                                return View(model);
                            }

                            //找到当前项目的根项目记录
                            string rootProjectCode = _this_project.proj_code;
                            if (rootProjectCode.IndexOf("/") >= 0)
                            {
                                rootProjectCode = rootProjectCode.Remove(rootProjectCode.IndexOf("/"));
                            }

                            //查询项目列表
                            var _this_level_projects = session.QueryOver<DB_NH.DB_Model.ywxt.t_project>()
                                .Where(c => c.is_valid == 1 &&
                                        c.proj_code.IsLike(rootProjectCode + "%") &&
                                        c.is_leaf == 1)
                                .OrderBy(c => c.proj_code).Asc()
                                .List();

                            //清空当前的列表
                            model.thisExtractRefProjects.Clear();

                            foreach (var v in _this_level_projects)
                            {
                                //拼凑项目名称
                                string _projName = v.proj_code;
                                if (_projName.IndexOf("/") > 5)
                                {
                                    _projName = _projName.Substring(_projName.IndexOf("/") - 5);
                                }
                                else
                                {
                                    _projName = _projName.Substring(_projName.Length - 5);
                                }

                                _projName += v.proj_name;

                                //生成对应记录
                                ExpertConfirm.RefProject _refProject = new ExpertConfirm.RefProject()
                                {
                                    projectID = v.proj_id,
                                    projectCode = v.proj_code,
                                    projectName = _projName,
                                    projectIsSelected = false
                                };

                                //判断当前的项目记录是否条件中设置的项目，如果是，默认为选中
                                _refProject.projectIsSelected = (_refProject.projectID == _this_selected_project_id);

                                //添加到项目备选列表
                                model.thisExtractRefProjects.Add(_refProject);
                            }
                            transaction.Commit();
                            #endregion

                            return View(model);
                        }
                    }
                    #endregion
                }
                else if (model.opFlag == ExpertConfirm.OPType.QUERY_EXPERT_LIST)
                {
                    #region 当前操作是查询专家列表
                    string professional = model.Q_professional;
                    string categoryId = model.Q_category_id;

                    //专业与专家关联表
                    //List<DB_NH.DB_Model.ZJK.ZJ_expert> expertList=new List<DB_NH.DB_Model.ZJK.ZJ_expert>();

                    var sessionFactory = SessionFactory.GetCurrentFactory();
                    using (var session = sessionFactory.OpenSession())
                    {
                        using (var transaction = session.BeginTransaction())
                        {
                            var query = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_expert>()
                                .Where(c => c.IsValid == 1);

                            //处理专家分类条件
                            if (!string.IsNullOrEmpty(categoryId))
                            {
                                var _category = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_category>()
                                    .Where(c => c.Id == categoryId)
                                    .SingleOrDefault();
                                if (_category != null)
                                {
                                    List<string> exp_ids = new List<string>();
                                    foreach (var item in _category.zj_experts)
                                    {
                                        exp_ids.Add(item.Id);
                                    }
                                    query = query.And(c => c.Id.IsIn(exp_ids));
                                }
                            }

                            //处理专家专业
                            if (!string.IsNullOrEmpty(professional))
                            {
                                query = query.And(c => c.zj_professional.IsLike("%" + professional + "%") &&
                                    c.IsValid == 1);
                            }

                            if (string.IsNullOrEmpty(model.Q_name))
                            {
                                model.Q_name = string.Empty;
                            }
                            if (string.IsNullOrEmpty(model.Q_phone))
                            {
                                model.Q_phone = string.Empty;
                            }

                            var expertList = query
                                .OrderBy(c => c.zj_name).Asc()
                                .And(c =>
                                    c.zj_name.IsLike("%" + model.Q_name + "%") &&
                                    (c.zj_mobile.IsLike("%" + model.Q_phone + "%") ||
                                     c.zj_tele_home.IsLike("%" + model.Q_phone + "%") ||
                                     c.zj_tele_work.IsLike("%" + model.Q_phone + "%")))
                                .List();
                            transaction.Commit();

                            //生成model的专家备选列表
                            model.expertList_bx.Clear();
                            foreach (var v in expertList)
                            {
                                ExpertConfirm.ViewModelExpert _expert = new ExpertConfirm.ViewModelExpert()
                                {
                                    expertID = v.Id.ToString(),
                                    expertCategory = string.Empty,
                                    expertMobile = v.zj_mobile,
                                    expertName = v.zj_name,
                                    expertPhone = v.zj_tele_home,
                                    expertProfession = v.zj_professional
                                };

                                model.expertList_bx.Add(_expert);
                            }
                            return View(model);
                        }
                    }


                    #endregion
                }
                else if (model.opFlag == ExpertConfirm.OPType.ADD_THIS_EXPERT)
                {
                    #region 当前操作是添加当前的专家信息到抽取列表中
                    if (!string.IsNullOrEmpty(model.opThisExpertID))
                    {
                        var sessionFactory = SessionFactory.GetCurrentFactory();
                        using (var session = sessionFactory.OpenSession())
                        {
                            using (var transaction = session.BeginTransaction())
                            {
                                DB_NH.DB_Model.ZJK.ZJ_expert thisExpert = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_expert>()
                                    .Where(c => c.IsValid == 1 && c.Id == model.opThisExpertID)
                                    .SingleOrDefault();

                                if (thisExpert != null)
                                {
                                    var _thisViewModelExpert = new ExpertConfirm.ViewModelExpert()
                                    {
                                        expertCategory = string.Empty,
                                        expertID = thisExpert.Id,
                                        expertMobile = thisExpert.zj_mobile,
                                        expertName = thisExpert.zj_name,
                                        expertPhone = thisExpert.zj_tele_home,
                                        expertProfession = thisExpert.zj_professional
                                    };

                                    var _thisViewModelExtract = new ExpertConfirm.ViewModelExtract()
                                    {
                                        expertInfo = _thisViewModelExpert,
                                        extractIsSucessed = 1,
                                        extractLog = @"系统初始化中……
拨号……
播放信息提示语音……
等待用户按键（1：同意、0：不同意；）……
接收到用户按键：1（同意）
系统播放确认语音……
系统自主挂机，完成本次操作。",
                                        ID = Common.NewID()
                                    };

                                    //添加到model的专家抽取列表中
                                    model.extractList.Add(_thisViewModelExtract);
                                }
                                else
                                {
                                    TempData[Common.CONST_TEMPDATA_INF] = "专家记录未找到！";
                                    return View(model);
                                }
                                transaction.Commit();

                                return View(model);
                            }
                        }
                    }
                    else
                    {
                        TempData[Common.CONST_TEMPDATA_INF] = "参数错误";
                        return View(model);
                    }
                    #endregion
                }
                else if (model.opFlag == ExpertConfirm.OPType.DELETE_THIS_EXTRACT)
                {
                    #region 当前操作是删除当前选定的抽取记录
                    if (!string.IsNullOrEmpty(model.opThisExtractID))
                    {
                        //循环列表，删除当前ID的抽取记录
                        foreach (var _item in model.extractList)
                        {
                            if (_item.ID == model.opThisExtractID)
                            {
                                model.extractList.Remove(_item);
                                break;
                            }
                        }
                        return View(model);
                    }
                    else
                    {
                        TempData[Common.CONST_TEMPDATA_INF] = "参数错误";
                        return View(model);
                    }
                    #endregion
                }
                else if (model.opFlag == ExpertConfirm.OPType.SAVE_THIS_PROJECT_EXTRACT)
                {
                    //保存当前项目的抽取记录备选信息

                    #region 获取基础信息
                    //获取当前操作用户
                    var _thisUser = getCurrentUser();

                    //判断关联项目是否设置
                    if (model.thisExtractRefProjects.Count <= 0)
                    {
                        if (string.IsNullOrEmpty(model.Q_project_id))
                        {
                            TempData[Common.CONST_TEMPDATA_INF] = "关联项目未选择！";
                            return View(model);
                        }
                        else
                        {
                            using (var session = SessionFactory.GetCurrentFactory().OpenSession())
                            {
                                using (var transaction = session.BeginTransaction())
                                {
                                    //当前查询的项目作为默认的关联项目
                                    var _thisProject = session.QueryOver<DB_NH.DB_Model.ywxt.t_project>()
                                        .Where(c => c.is_valid == 1 && c.proj_id == model.Q_project_id)
                                        .SingleOrDefault();
                                    if (_thisProject != null)
                                    {
                                        model.thisExtractRefProjects.Add(new ExpertConfirm.RefProject()
                                        {
                                            projectID = _thisProject.proj_id,
                                            projectCode = _thisProject.proj_code,
                                            projectIsSelected = true,
                                            projectName = model.Q_project_name
                                        });
                                    }
                                    transaction.Commit();
                                }
                            }
                        }
                    }

                    int x = 0;
                    foreach (var v in model.thisExtractRefProjects)
                    {
                        if (v.projectIsSelected) x++;
                    }

                    //设置抽取标题
                    string _thisExtractBak_title = DateTime.Today.ToString("yyyy-MM-dd") + " 用户" + _thisUser.user_truename_cn + "设置" +
                        model.thisExtractRefProjects.First().projectName + "等" +
                        x.ToString() + "个项目的抽取设置。";
                    #endregion

                    #region 是否允许保存
                    string _msg = string.Empty;

                    int _selectedProjectCount = 0;
                    foreach (var _item in model.thisExtractRefProjects)
                    {
                        if (_item.projectIsSelected)
                        {
                            _selectedProjectCount++;
                        }
                    }
                    if (_selectedProjectCount > 0)
                    {

                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(model.Q_project_id))
                        {
                            _selectedProjectCount = 1;
                        }
                        _msg = "关联项目未选择。";
                    }

                    if (model.extractList.Count > 0)
                    {

                    }
                    else
                    {
                        if (string.IsNullOrEmpty(_msg))
                        {
                            _msg = "备选专家未选择！";
                        }
                        else
                        {
                            _msg += "\\r\\n备选专家未选择！";
                        }
                    }

                    if (!string.IsNullOrEmpty(_msg))
                    {
                        TempData[Common.CONST_TEMPDATA_INF] = "因为以下原因，不能进行保存操作：\\r\\n" + _msg;
                        return View(model);
                    }
                    #endregion

                    var sessionFactory = SessionFactory.GetCurrentFactory();
                    using (var session = sessionFactory.OpenSession())
                    {
                        using (var transaction = session.BeginTransaction())
                        {
                            try
                            {
                                #region 当前操作是保存的项目抽取备选记录
                                //1、生成并保存抽取记录
                                var _thisExtractBak = new DB_NH.DB_Model.ZJCQ.ZJ_extract_bak()
                                {
                                    CreateDate = DateTime.Now,
                                    IsValid = 1,
                                    title = _thisExtractBak_title,
                                    user = _thisUser
                                };

                                //2、生成抽取与项目关联记录
                                _thisExtractBak.zj_extract_bak_projects.Clear();
                                foreach (var _item in model.thisExtractRefProjects)
                                {
                                    if (!string.IsNullOrEmpty(_item.projectID) && _item.projectIsSelected)
                                    {


                                        //获取当前的项目信息
                                        DB_NH.DB_Model.ywxt.t_project _thisProject = session.QueryOver<DB_NH.DB_Model.ywxt.t_project>()
                                            .Where(c => c.is_valid == 1 && c.proj_id == _item.projectID)
                                            .SingleOrDefault();

                                        if (_thisProject != null)
                                        {
                                            //清除当前项目对应的抽取备选记录
                                            _thisProject.proj_extract_baks.Clear();

                                            //添加当前对应的抽取备选记录
                                            _thisProject.proj_extract_baks.Add(_thisExtractBak);

                                            /*
                                            //查询当前项目是否有关联的备选抽取记录
                                            var _this_proj_extracts = session.QueryOver<DB_NH.DB_Model.ZJCQ.ZJ_extract_bak>()
                                                .Where(c => c.IsValid == 1)
                                                .JoinQueryOver<DB_NH.DB_Model.ywxt.t_project>(c => c.zj_extract_bak_projects)
                                                .Where(p => p.proj_id == _thisProject.proj_id)
                                                .List();

                                            //逐一清除当前关联的记录
                                            foreach (var _extract in _this_proj_extracts)
                                            {
                                                for (int i = _extract.zj_extract_bak_projects.Count - 1; i >= 0; i--)
                                                {
                                                    if (_extract.zj_extract_bak_projects[i] == _thisProject)
                                                    {
                                                        _extract.zj_extract_bak_projects.RemoveAt(i);
                                                    }
                                                }

                                            }
                                             */

                                            _thisExtractBak.zj_extract_bak_projects.Add(_thisProject);

                                        }
                                        else
                                        {
                                            continue;
                                        }
                                    }
                                    else
                                    {
                                        continue;
                                    }
                                }

                                //3、生成并保存抽取详细记录
                                int _orderFlag = 0;
                                foreach (var _item in model.extractList)
                                {
                                    //获取专家信息
                                    var _thisExpert_temp = session.QueryOver<DB_NH.DB_Model.ZJK.ZJ_expert>()
                                        .Where(c => c.Id == _item.expertInfo.expertID && c.IsValid == 1)
                                        .SingleOrDefault();

                                    if (_thisExpert_temp != null)
                                    {
                                        DB_NH.DB_Model.ZJCQ.ZJ_extract_detail_bak _thisDetail = new DB_NH.DB_Model.ZJCQ.ZJ_extract_detail_bak()
                                        {
                                            CreateDate = DateTime.Now,
                                            expert = _thisExpert_temp,
                                            extract_bak = _thisExtractBak,
                                            is_selected = _item.extractIsSucessed,
                                            IsValid = 1,
                                            order_flag = _orderFlag,
                                            un_selected_msg = _item.extractLog
                                        };
                                        _thisDetail.extract_bak = _thisExtractBak;
                                        _thisExtractBak.details.Add(_thisDetail);
                                        session.SaveOrUpdate(_thisDetail);
                                        _orderFlag++;
                                    }
                                    else
                                    {
                                        continue;
                                    }
                                }

                                //3、保存抽取记录
                                session.SaveOrUpdate(_thisExtractBak);

                                #endregion
                                transaction.Commit();
                                TempData[Common.CONST_TEMPDATA_INF] = "项目抽取设置完成！";
                                return RedirectToAction("ConfirmList");
                            }
                            catch (Exception _ex)
                            {
                                TempData[Common.CONST_TEMPDATA_ERR] = _ex.Message;
                                return View(model);
                            }
                        }
                    }
                }

                return View(model);

            }

            return View();
        }
        #endregion

        /// <summary>
        /// 判断当前专家信息是否允许保存
        /// </summary>
        /// <param name="_expert"></param>
        /// <returns></returns>
        private bool ExpertIsCanSave(DB_NH.DB_Model.ZJK.ZJ_expert _expert, out string _msg)
        {
            _msg = string.Empty;
            bool _returnValue = true;

            //检查姓名
            if (string.IsNullOrEmpty(_expert.zj_name))
            {
                _returnValue = false;
                if (string.IsNullOrEmpty(_msg))
                {
                    _msg = "姓名不能为空。";
                }
                else
                {
                    _msg += @"\r\n姓名不能为空。";
                }
            }

            //检查专业
            if (string.IsNullOrEmpty(_expert.zj_professional))
            {
                _returnValue = false;
                if (string.IsNullOrEmpty(_msg))
                {
                    _msg = "专业不能为空。";
                }
                else
                {
                    _msg += @"\r\n专业不能为空。";
                }
            }

            //检查工作单位
            if (string.IsNullOrEmpty(_expert.zj_name))
            {
                _returnValue = false;
                if (string.IsNullOrEmpty(_msg))
                {
                    _msg = "工作单位不能为空。";
                }
                else
                {
                    _msg += @"\r\n工作单位不能为空。";
                }
            }

            //检查联系电话
            if (string.IsNullOrEmpty(_expert.zj_name))
            {
                _returnValue = false;
                if (string.IsNullOrEmpty(_msg))
                {
                    _msg = "联系电话不能为空。";
                }
                else
                {
                    _msg += @"\r\n联系电话不能为空。";
                }
            }
            return _returnValue;
        }

        /// <summary>
        /// 获取当前的登录用户
        /// </summary>
        /// <returns></returns>
        private DB_NH.DB_Model.ywxt.t_sys_user getCurrentUser()
        {
            #region 获取当前登录用户
            var sessionFactory = SessionFactory.GetCurrentFactory();
            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {

                    string _this_user_name_en = Common.getAuthenticatedUser(User).Name;
                    string _this_user_name_cn = Common.getAuthenticatedUser(User).DisplayName;

                    var _this_user = session.QueryOver<DB_NH.DB_Model.ywxt.t_sys_user>()
                        .Where(c => c.is_valid == 1
                            && c.user_truename_en == _this_user_name_en
                            && c.user_truename_cn == _this_user_name_cn)
                        .SingleOrDefault();

                    if (_this_user != null)
                    {
                        transaction.Commit();
                        return _this_user;
                    }
                    else
                    {
                        transaction.Rollback();
                        return null;
                    }
                }
            }
            #endregion
        }
    }
}
